/**
 * Created by tdzl2003 on 6/23/16.
 */

import React, { PropTypes } from 'react';
import {
  ListView,
} from 'react-native';

export default class DataListView extends React.Component {
  static propTypes = {
    ...ListView.propTypes,
    dataSource: PropTypes.any,
    renderScrollComponent: PropTypes.any,

    fetchData: PropTypes.func,
  }
  state = {
    data: [],
    page: 0,
    dataSource: new ListView.DataSource({ rowHasChanged: (r1, r2) => (r1 !== r2) }),
    isFetching: false,
    isOver: false,
  };
  async componentDidMount() {
    this.refreshData();
  }
  componentWillReceiveProps(newProps) {
    if (
      [
        'fetchData',
      ].some(k => newProps[k] !== this.props[k])) {
      this.refreshData();
    }
  }

  fetchData = async () => {
    const { page, data, dataSource, isFetching, isOver } = this.state;
    const { fetchData } = this.props;
    if (isOver || isFetching) {
      return;
    }
    const { total, result } = await fetchData(page + 1);
    const newData = data.concat(result);
    this.setState({
      page: page + 1,
      data: newData,
      dataSource: dataSource.cloneWithRows(newData),
      isOver: newData.length >= total || result.length === 0,
    });
  };

  refreshData = async () => {
    await new Promise(resolve => this.setState({
      data: [],
      page: 0,
      isFetching: false,
      isOver: false,
      dataSource: this.state.dataSource.cloneWithRows([]),
    }, resolve));
    return await this.fetchData();
  };

  renderFooter = () => {
    const { isOver, data } = this.state;
    const { placeholder } = this.props;
    if (isOver && data.length === 0) {
      return placeholder;
    }
    return null;
  };

  render() {
    const { ...others } = this.props;
    return (
      <ListView
        {...others}
        onEndReached={this.fetchData}
        dataSource={this.state.dataSource}
        renderFooter={this.renderFooter}
      />
    );
  }
}
